package com.github.sbb.sherry.primitives.rules.flow;

import com.alibaba.fastjson.JSON;
import com.github.sbb.sherry.common.collect.CollectionUtil;
import com.github.sbb.sherry.primitives.rules.FlowRuleTypeEnum;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FlowRulesParser {

  public static FlowRules parse(String json) {
    FlowRulesConfig flowRulesConfig = JSON.parseObject(json, FlowRulesConfig.class);

    List<FlowRulesConfigLine> lineList = flowRulesConfig.getLineList();

    Set<String> maybeVisitedNodes = new HashSet<>();
    for (FlowRulesConfigLine flowRulesConfigLine : lineList) {
      maybeVisitedNodes.add(flowRulesConfigLine.getFrom());
      maybeVisitedNodes.add(flowRulesConfigLine.getTo());
    }

    // 删除不可能的节点
    flowRulesConfig.getNodeList().removeIf(it -> !maybeVisitedNodes.contains(it.getId()));

    // 找到开始节点
    String processStartCode = FlowRuleTypeEnum.PROCESS_START.getCode();
    List<FlowRulesConfigNode> startFlowRules = flowRulesConfig.getNodeList().stream()
        .filter(it -> it.getType().equals(processStartCode)).collect(Collectors.toList());

    if (CollectionUtil.isEmpty(startFlowRules) || startFlowRules.size() > 1) {
      throw new IllegalArgumentException("解析失败，未发现主节点或主节点不唯一");
    }

    List<FlowRule> flowRules = new ArrayList<>();
    for (FlowRulesConfigNode flowRulesConfigNode : flowRulesConfig.getNodeList()) {
      FlowRule flowRule = new FlowRule();
      flowRule.setId(flowRulesConfigNode.getId());
      flowRule.setName(flowRulesConfigNode.getName());
      flowRule.setType(FlowRuleTypeEnum.getByCode(flowRulesConfigNode.getType()));
      flowRule.setMaxExecuteTime(flowRulesConfigNode.getMaxExecuteTime());

      // TODO yunan 这里没有处理完

      if (flowRule.getType() == FlowRuleTypeEnum.PROCESS_START) {
        flowRules.add(0, flowRule);
      } else {
        flowRules.add(flowRule);
      }
    }
    return new FlowRules(flowRules.get(0), flowRules, flowRulesConfig);
  }
}
